package com.jc.oms.controller.task.productImg;

import com.jc.cds.model.CustomSupplierGoodsPictureList;
import com.jc.common.util.DateTimeUtil;
import com.jc.common.util.ExceptionUtil;
import com.jc.common.util.ImageUtil;
import com.jc.common.util.UrlUtil;
import com.jc.ds.model.SupplierGoods;
import com.jc.ds.model.SupplierGoodsPictureList;
import com.jc.ds.model.SupplierProduct;
import com.jc.framework.enums.ImageType;
import com.jc.framework.enums.LogType;
import com.jc.framework.enums.ThirdPartyParam;
import com.jc.framework.util.PropertyPlaceholder;
import com.jc.framework.util.SpringUtils;
import com.jc.oms.controller.BaseController;
import com.jc.service.h5.ShopService;
import com.jc.service.model.h5.H5RespModel;
import com.jc.service.suppliergoods.SupplierGoodsService;
import com.jc.service.suppliergoodspicturelist.SupplierGoodsPictureListService;
import com.jc.service.supplierproduct.SupplierProductService;
import com.jc.service.task.productImg.ProductImageService;
import com.jc.upload.aliyun.oos.AliyunOssUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 图片压缩定时
 * wb
 * */
@SuppressWarnings("all")
@Controller
@RequestMapping("productImage")
public class ProductImageController  extends BaseController{
    @Autowired
    private ProductImageService productImageService;

    private SupplierGoodsPictureListService supplierGoodsPictureListService = SpringUtils.getBean(SupplierGoodsPictureListService.class);

    private ShopService shopService = SpringUtils.getBean(ShopService.class);


    @RequestMapping(value="compressionImg",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> compressionImg(){
        Map<String,Object> resultMap = new HashMap<>();
        try{
            productImageService.compressionImg();
            resultMap.put("success", true);
        }catch (Exception e){
            resultMap.put("success", false);
            resultMap.put("errorMsg", ExceptionUtil.subExceptionMessage(e, 0, 100));
        }
       return resultMap;
    }
    //compressionImgtemp
    
    
    @RequestMapping(value="compressionImg2",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> compressionImgtemp(){
        Map<String,Object> resultMap = new HashMap<>();
        try{
            productImageService.compressionImgtemp();
            resultMap.put("success", true);
        }catch (Exception e){
            resultMap.put("success", false);
            resultMap.put("errorMsg", ExceptionUtil.subExceptionMessage(e, 0, 100));
        }
       return resultMap;
    }


    private static List<String> detailList = new ArrayList<>();
    private static List<String> picList = new ArrayList<>();
    private static List<Long> ids = new ArrayList<>();
    private static Integer start = -100;
    private static Integer limit = 100;
    private static  Boolean flag = true;
    private static  Integer x = 0;

    @Autowired
    private SupplierGoodsService supplierGoodsService;

//    private static int POOL_NUM = 5;     //线程池数量

    @RequestMapping(value = "/updateShopImg" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateShopImg(){
        Map<String, Object> returnMap = new HashMap<>();
        start = -100;
        flag = true;
        detailList = new ArrayList<>();
        picList = new ArrayList<>();
        ids = new ArrayList<>();
        try{


//            while (true){
                int i1 = supplierGoodsService.queryAllCount(new SupplierGoods());
//                if (i1 > (start + limit) * limit +1){
//                }
//                if (flag){
//                int du = i1/limit;
                BigDecimal bigDecimal = new BigDecimal(i1).divide(new BigDecimal(limit)).setScale(1, BigDecimal.ROUND_UP);
                String s = bigDecimal.toString();
                Integer substring = Integer.valueOf(s.substring(s.length() - 1, s.length()));

                Integer frequency = Integer.valueOf(s.substring(0, s.length() - 2));
                if (substring > 0){
                    frequency++;
                }

//            List<SupplierGoods> supplierGoods = supplierGoodsService.queryAll(new SupplierGoods());
            String  a = "13089";
            String[] split = a.split(",");

            for (String supplierGood:split) {
                x++;
                System.out.println("=====================当前产品Id : "+supplierGood);
//                System.out.println("======================第"+ x +"个产品===============剩余 : "+ (split.length()- x)+"个");
                try{
                    uploadImg(Long.valueOf(supplierGood));
                    System.out.println("================== 图片上传完成!!!!!!!!!!!!");
                }catch (Exception e){
                    System.out.println("==============遇到异常 "+e.getLocalizedMessage());
                    continue;
                }
            }

            System.out.println("==================完后!!!!!!!!!!!!!!!!!!!!");
            x = 0;
            for (String b :split) {
//                System.out.println("=====================推送商城当前产品Id : "+ b.getId());
                System.out.println("======================推送商城第"+ x+++"个产品===============");
                detailList = new ArrayList<>();
                picList = new ArrayList<>();
                try{
                    List<SupplierGoodsPictureList> supplierGoodsPictureLists = supplierGoodsPictureListService.queryAll(new SupplierGoodsPictureList() {{
                        setGid(Long.valueOf(b));
                    }});
                    for (SupplierGoodsPictureList supplierGoodsPictureList:supplierGoodsPictureLists) {
                        if (supplierGoodsPictureList.getImageType() == ImageType.DETAILS.getName()){
                            //详情图
                            detailList.add(supplierGoodsPictureList.getSelfImagePath());
                        }else if (supplierGoodsPictureList.getImageType() == ImageType.ROTATION.getName()){
                            //轮播图
                            detailList.add(supplierGoodsPictureList.getSelfImagePath());
                        }
                    }
                    H5RespModel h5RespModel = shopService.pushH5(ThirdPartyParam.UPDATE_PRO_IMG_H5.getName(), new HashMap<String, Object>() {{
                        put("productCode", b);
                        put("pics", StringUtils.join(picList, ";"));
                        put("details", StringUtils.join(detailList, ";"));
                    }}, LogType.PUSH_H5_UPDATE_IMG_PRO);
                }catch (Exception e){
                    System.out.println("=============推送图片信息到商城出现异常 : "+ e.getLocalizedMessage());
                    continue;
                }
                Thread.sleep(1000);
            }
//                final CountDownLatch latch = new CountDownLatch(frequency);
//
//                ExecutorService executorService = Executors.newFixedThreadPool(frequency);

//              for(int i = 0; i<frequency; i++){
//                    x++;
//                    ProductImageController thread = new ProductImageController();
//                    //Thread.sleep(1000);
//                    executorService.execute(thread);
//                    System.out.println("==================开启了 "+x+"个线程");
//                }
//                }else{
//                    x++;
//                    ProductImageController thread = new ProductImageController();
//                    //Thread.sleep(1000);
//                    executorService.execute(thread);
//                    System.out.println("==================开启了 "+x+"个线程");
//                    break;
//                }
//            }
//            latch.await();
//            executorService.shutdown();



            getLoger().debug("==========所有子线程执行完毕 , 继续主线程!!!!!");
//            //关闭线程池
            System.out.println(ids);

            System.out.println("=====================================同步图片结束!!!!!!!!");
        }catch (Exception e){
            getLoger().error("修改图片出错");
            e.printStackTrace();
        }
        return returnMap;
    }





    public void uploadImg(Long gid) throws Exception {
        start = start + limit;
        getLoger().error("当前线程分页起始值为 "+ start);
        //获取所有的图片
//        List<SupplierGoodsPictureList> supplierGoodsPictureLists = supplierGoodsPictureListService.queryLimitAll(new CustomSupplierGoodsPictureList(){{
//            setStart(start);
//            setLimit(limit);
//        }});
        List<SupplierGoodsPictureList> supplierGoodsPictureLists = supplierGoodsPictureListService.queryAll(new SupplierGoodsPictureList(){{
            setGid(gid);
        }});
        if (CollectionUtils.isEmpty(supplierGoodsPictureLists)){
            flag = false;
            return ;
        }
        for (SupplierGoodsPictureList img:supplierGoodsPictureLists) {
            if (!ids.contains(img.getGid())){
                ids.add(img.getGid());
            }
            //原图片地址
            String imagePath = img.getImagePath();

//            String localPath = "/usr/local/static/img/";
//            String datestr = DateTimeUtil.getDate(new Date(), "yyyyMMdd");
//            String path = localPath + datestr;
            //获取图片大小
//            String name = UUID.randomUUID().toString().replaceAll("-", "");
//            String extName = UrlUtil.getFileExtension(imagePath);
//            String notZipFilePath = path + "/" + name + "." + extName;
//            String zipFilePath = path + "/" + "zip" + name + "." + extName;
//            ImageUtil.downloadPicture(imagePath, notZipFilePath);

            String s = imageZipUpload(imagePath);
            if (img.getImageType() == ImageType.DETAILS.getName()){
                //详情图
                supplierGoodsPictureListService.modify(new SupplierGoodsPictureList(){{
                    setId(img.getId());
                    setSelfImagePath(s);
                }},false);
            }else if (img.getImageType() == ImageType.ROTATION.getName()){
                //轮播图
                supplierGoodsPictureListService.modify(new SupplierGoodsPictureList(){{
                    setId(img.getId());
                    setSelfImagePath(s);
                }},false);
            }
//            String localPath = "/usr/local/static/img/";
//            String datestr = DateTimeUtil.getDate(new Date(), "yyyyMMdd");
//            String path = localPath + datestr;
//            File dir = new File(path);
//            if (!dir.exists()) {
//                dir.mkdirs();
//            }
//            String name = UUID.randomUUID().toString().replaceAll("-", "");
//            String extName = UrlUtil.getFileExtension(imagePath);
//            String notZipFilePath = path + "/" + name + "." + extName;
//            String zipFilePath = path + "/" + "zip" + name + "." + extName;
//            ImageUtil.downloadPicture(imagePath, notZipFilePath);
//
//            File file = new File(notZipFilePath);
//            long imgSize = file.length();
//            //获取不压缩图片的大小
//            Long compressionSize = Long.valueOf(String.valueOf(PropertyPlaceholder.getProperty("compression.size")));
//            if (imgSize <= compressionSize){
//                //小于300M 直接上传 .
//                AliyunOssUtil util = new AliyunOssUtil();
//                String imageURL = util.uploadImg2Oss(file);
//
//                //删除
//                file.delete();
//
//
//            }else{
//
//            }
        }
//        threadsSignal.countDown();
    }


    public String imageZipUpload(String remoteUrl) {
        String localPath = "/usr/local/static/img/";
        String datestr = DateTimeUtil.getDate(new Date(), "yyyyMMdd");
        try {
            String path = localPath + datestr;
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String name = UUID.randomUUID().toString().replaceAll("-", "");
            String extName = UrlUtil.getFileExtension(remoteUrl);
            String notZipFilePath = path + "/" + name + "." + extName;
            String zipFilePath = path + "/" + "zip" + name + "." + extName;
            ImageUtil.downloadPicture(remoteUrl, notZipFilePath);
            String localhostPath = "";
            try {
                //获取图片大小
                long imgSize = new File(notZipFilePath).length();
                //获取不压缩图片的大小
                Long compressionSize = Long.valueOf(String.valueOf(PropertyPlaceholder.getProperty("compression.size")));
                if (imgSize <= compressionSize){
                    localhostPath = notZipFilePath;
                }else{
                    localhostPath = ImageUtil.outputQuality(notZipFilePath, 0.5, zipFilePath, new BigDecimal("250"));
                }
            }catch (Exception e) {
                getLoger().error("压缩图片错误: {},{}",e.getMessage(),e);
            }
            if(StringUtils.isBlank(localhostPath)) {
                return "";
            }
            // 上传    13235
            File file = new File(localhostPath);
            AliyunOssUtil util = new AliyunOssUtil();
            String imageURL = util.uploadImg2Oss(file);
            //上传完成删除本地服务器图片
            file.delete();
            File notZipFile = new File(notZipFilePath);
            notZipFile.delete();
            getLoger().debug("删除服务器图片:"+localhostPath);
            return imageURL;
        } catch (Exception e) {
            getLoger().error("压缩上传图片出现错误, 图片源地址: {} , 错误原因: {},{}", remoteUrl, e.getMessage(), e);
        }
        return null;
    }

//    @Override
//    public void run() {
//        try {
//            uploadImg();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
